﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace BLL
{
    public class TCPComm
    {
        BLL.recDataDeal b_recDataDeal = new recDataDeal();
        private string modeId;
        public void setModeId (string modeIdGet)
        {
            this.modeId = modeIdGet;
        }

        #region 定义socket通讯 等变量
        IPEndPoint point;
        Socket socket;
        bool flag = true;
        public Socket acceptedSocket;
       // public string dataRec;
        public static Thread threadComm;    //等待客户连接线程
        public static Thread chkThread;     //判断接受数据是否为新的 线程
        //socket接受数据的属性
        public string dataRec { get; set; }
        #endregion         

        #region 建立socket 绑定输入ip地址、侦听、接受连接
        /// <summary>
        /// 建立socket 绑定输入ip地址、侦听、接受连接
        /// socket使用 参考下面网址 
        /// http://www.csharpwin.com/csharpspace/2265.shtml
        /// </summary>
        /// <param name="ip">字符串格式ip</param>
        public void openComm(string ip,string port)
        {
            //IPAddress HostIP = IPAddress.Parse(ip);
            //try
            //{
            //    point = new IPEndPoint(HostIP, Int32.Parse("8002"));
            //    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //    socket.Bind(point);
            //    socket.Listen(50);
            //    acceptedSocket = socket.Accept();
            //    threadComm = new Thread(new ThreadStart(commProccess)); //等待客户连接线程
            //    chkThread = new Thread(new ThreadStart(dataRecPro));    //判断接受数据是否为新的 线程
            //    chkThread.Start();
            //    threadComm.Start();
            //}
            //catch
            //{
            //}

            //HostIP = IPAddress.Parse(textBoxIP.Text.Trim());
            //HostIP = IPAddress.Parse("192.168.1.1");
            IPAddress HostIP = IPAddress.Parse(ip);
            try
            {
                point = new IPEndPoint(HostIP, Int32.Parse(port));
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(point);
                //chkThread = new Thread(new ThreadStart(dataRecPro));    //判断接受数据是否为新的 线程
                //chkThread.Start();
                threadComm = new Thread(new ThreadStart(commProccess));
                threadComm.Start();
            }
            catch 
            {
               // MessageBox.Show("服务器没有开启/r/n" + ey.Message);
            }
        }
        #endregion        
        Model.modeIdAndArea m_modeIdAndArea = new Model.modeIdAndArea();
        #region 接受客户机socket 发送过来的字节数组 接受数据格式为：ASCII 编码
        public void commProccess()
        {
            if (socket.Connected)
            {
                string temp = "";
                string strInfo = "";
                string temp2 = "";
                string headCode = "AA";
                string endCode = "55";
                string cutY = "";
                while (flag)
                {
                    try
                    {                        
                        byte[] receiveByte = new byte[100];
                        socket.Receive(receiveByte, receiveByte.Length, 0);
                        strInfo = Encoding.ASCII.GetString(receiveByte);
                        strInfo = strInfo.TrimEnd('\0');
                        strInfo = strInfo.Replace("\r", "");
                        strInfo = strInfo.Replace("\n", "");
                        strInfo = strInfo.Replace("-", "");
                        //cutY = strInfo.Substring(strInfo.IndexOf("Y"), 3);
                        //strInfo = strInfo.Replace(cutY, "");

                        temp += strInfo;

                        if (temp.Substring(0, 2) == headCode && temp.Substring(23, 2) == endCode)
                        {
                            temp2 = temp.Substring(0, 25);
                            temp = temp.Substring(25);
                            b_recDataDeal.dataDeal(temp2, this.modeId);
                            Thread.Sleep(50);
                        }
                        if (temp.Substring(0, 1) == "E" && (temp.Substring(6, 1) == "1" || temp.Substring(6, 1) == "0"))
                        {
                            temp2 = temp.Substring(0, 7);
                            temp = temp.Substring(7);
                            b_recDataDeal.macAction(temp2);
                            Thread.Sleep(50);
                        }
                    }
                    catch
                    {
                    }
                }
            }
        } 
	    #endregion
        

        #region 发送数据 +sendData(string sendStr)
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sendStr">指令</param>
        public void sendData(string sendStr)
        {
            try
            {
                Byte[] sendByte = new Byte[64];
                //ASCII 编码 
                sendByte = Encoding.ASCII.GetBytes(sendStr.ToCharArray());
                string bytString = "";
                for (int i = 0; i < sendByte.Length; i++)
                {
                    bytString += sendByte[i];
                }

                socket.Send(sendByte, sendByte.Length, 0);
            }
            catch { }
        } 
        #endregion

        #region 关闭socket +closeSocket()
        public void closeSocket()
        {
            //acceptedSocket.Close();
            socket.Close();
        } 
        #endregion
    }
}
